/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.interceptor;

import org.apache.ibatis.aapl.annotation.EnhanceAfterQuery;
import org.apache.ibatis.aapl.annotation.strategy.EnhanceAfterQueryStrategy;
import org.apache.ibatis.aapl.registry.MethodRegistry;
import org.apache.ibatis.aapl.registry.SqlMethod;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gu
 * @date 2020/4/7 15:19
 */
public class EnhanceAfterQueryProcessor implements ResultSetProcessor {

  private static Logger log = LoggerFactory.getLogger(EnhanceAfterQueryProcessor.class);

  private MethodRegistry registry = MethodRegistry.getMethodRegistry();

  private Map<Class<? extends EnhanceAfterQueryStrategy>, EnhanceAfterQueryStrategy> strategyMap = new HashMap<>(32);

  @Override
  public void process(ResultSetHandler handler, List<Object> objs) {
    if (objs == null || objs.size() == 0 || !(handler instanceof DefaultResultSetHandler)) {
      return;
    }
    doProcess(handler, objs);
  }

  private void doProcess(ResultSetHandler handler, List<Object> objs) {
    SqlMethod method = registry.getMethod(((DefaultResultSetHandler) handler));

    EnhanceAfterQuery annotation = method.getMethod().getAnnotation(EnhanceAfterQuery.class);

    if (annotation == null) {
      return;
    }

    Class<? extends EnhanceAfterQueryStrategy>[] strategies = annotation.strategies();
    if (strategies.length <= 0) {
      return;
    }

    for (int i = 0; i < strategies.length; i++) {

      Class<? extends EnhanceAfterQueryStrategy> strategy = strategies[i];
      EnhanceAfterQueryStrategy realStrategy = strategyMap.computeIfAbsent(strategy, k -> {
        try {
          return strategy.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          log.warn("请确保 {} 存在public且参数为空的构造函数！", strategy);
          return null;
        }
      });

      if (realStrategy != null) {
        realStrategy.enhance(objs);
      }
    }
  }
}
